简体   繁体   中英

Problems with querying when a value is null

I am using php to query a database for one piece of information from each of 10 separate tables currently. The problem with using multiple queries is that it is extremely slow when accessing the web page that uses all of this information. I cannot seem to get all of the information back that I am wanting when one of the values does not exist due to the WHERE... statement.

For instance, my single queries are all in this format:

SELECT eval_id FROM eval WHERE user_id = $id;

My multiple table query looks like this:

SELECT eval_id,list_id,tab_id
FROM eval,list,tab
WHERE eval.user_id = $id
  AND list.user_id = $id
  AND tab.user_id = $id;

I tried to combine these queries into one large query, but when the user_id of one does not exist in the table, the comparison in the WHERE... statement screws up the entire query. Does anyone know the best way to retrieve all of this information?

Assume that the tables are "eval, list, and tab," and their id's are *_id respectively. What would be the best way to query this even if eval does not contain a result where the user_id = $id?

SELECT eval.eval_id, list.list_id
FROM user
JOIN eval ON eval.user_id = user.id
JOIN list ON list.user_id = user.id
WHERE user.id = $id

Hope it can help you.

Update: Just think about other solution:

SELECT eval_id as id, "eval" as table
FROM eval WHERE eval.user_id = $id

UNION

SELECT list_id as id, "list" as table
FROM list WHERE list.user_id = $id

You could use either of the following to your query in the WHERE statement:

AND TABLE.TABLE_id <> null //null 

AND TABLE.TABLE_id <> 'null' //String null

AND TABLE.TABLE_id <> '' //empty String

Check your database to see what kind of empty value your id is returning and choose the addition that matches it.

Also, while LEFT JOIN s may be better looking in a query, they are not always faster so make sure you test it before using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM