Good day everyone,
I want to ask a question about SQL I have 2 tables :
tuser (
id_user,
username,
password,
name,
level
)
tstatus(
id_status,
id_user,
status)
*tuser has 5 rows tstatus has 2 rows
i'm doing this query
SELECT *
FROM tuser,tstatus
WHERE tuser.id_user = tstatus.id_user
AND tuser.level = 'teacher'
AND tuser.name LIKE '%" . $queryString . "%'
ORDER BY tuser.name
LIMIT 5
The results from mysql_fetch_array only returns 2 rows of user data.
This is because the tstatus table has only 2 rows and could not match any id_user to join to in the tuser table, the problem here is to dynamically fill the tstatus fields can fill or null it..
Can somebody help me fix the query without modifying the table structure?
thanks
As best as I can understand you, I believe you're looking for something like this:
SELECT
*
FROM
tuser
LEFT JOIN
tstatus USING (id_user)
WHERE
tuser.level = 'teacher'
AND
tuser.name LIKE '%" . $queryString . "%'
ORDER BY
tuser.name
LIMIT 5
This will select all the users with a level of 'teacher' and a name that contains the query string -- even those which don't have a corresponding status (the value of any tstatus
field will be NULL
.
您可以进行左连接,以便所有tuser都在其中:
SELECT * FROM tuser left join tstatus on tuser.id_user = tstatus.id_user WHERE tuser.level = 'teacher' and tuser.name LIKE '%" . $queryString . "%' ORDER BY tuser.name LIMIT 5
use a left join instead.
SELECT tu.*, ts.status FROM tuser tu
LEFT JOIN tstatus ts ON tu.id_user = ts.id_user
WHERE tu.level ='teacher'
You may add other where statements as needed
use a left join. the USING keyword will remove the duplicate user_id field.
SELECT *
FROM tuser tu
LEFT JOIN tstatus ts USING (user_id)
WHERE tu.level ='teacher'
AND tuser.name LIKE '%" . $queryString . "%'
ORDER BY tuser.name
LIMIT 5
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.