0

I have this query:

SELECT st.st_id, st.id, st.name, at.status, at.date
FROM st,at
WHERE st.st_id = at.at_id;

but I want the result return all of st table, if st.st_id exist in at.st_id, the status column is what in the at table, if not the status is 'H', anyone can help? this is my table column

4
  • What is the foreign key for st table in at table at_id or st_id? I ask you this question because I don't understand why you say WHERE st.st_id = at.at_id; Commented Nov 1, 2017 at 2:22
  • Hi. Please: Read about formatting code. use text, not links/images, for text. Please read & act on minimal reproducible example. This is a faq and basic. Always google many clear, concise specific phrasings of your question/problem/goal without your application-specific names and read many hits; if you find no answer then use one phrasing as title. Read & act on How to Ask. Commented Nov 1, 2017 at 9:53
  • @PierreRobentzCassion One doesn't need to know FKs or any other constraints to query. Here we can just accept that they want status when st.st_id = at.at_id. It doesn't matter whether a FK could be or is declared between those columns or any other columns. (A FK could be declared when the referenced table is a PK or UNIQUE NOT NULL & the referenced column values are all in it.) Commented Nov 1, 2017 at 9:55
  • Possible duplicate of Replace null with 0 in MySQL Commented Nov 2, 2017 at 11:07

4 Answers 4

2

/Use IFNULL if DB is MYSQL/

SELECT st.st_id, st.id, st.name, IFNULL(at.status,'H') as status, at.date
FROM st LEFT JOIN
     at
     ON st.st_id = at.at_id;
Sign up to request clarification or add additional context in comments.

Comments

1

Never use commas in the FROM clause. Always use proper, explicit JOIN syntax. Then it would be easier to write the query:

SELECT st.st_id, st.id, st.name, COALESCE(at.status, 'H') as status, at.date
FROM st LEFT JOIN
     at
     ON st.st_id = at.at_id;

Comments

0

First let me try to understand what you want your query to do:

  1. The query must all st where st.st_id = at.at_id
  2. If st.st_id = at.st_id then at.status = status else status='H'

The script that I suggest:

SELECT st.st_id, st.id, st.name, IF(st.st_id = at.st_id, at.status, 'H') AS status, at.date FROM st LEFT JOIN at ON st.st_id = at.at_id;

Comments

0
   SELECT   st.st_id,
            st.id,
            st.name,
            st.cl_id,
            st.gender,
            CASE WHEN ISNULL(at.st_id ) THEN 'H' ELSE at.status
   FROM `st`
   LEFT JOIN `at` ON `st`.`st_id` = `at`.`st_id` 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.