简体   繁体   中英

Mysql search in 2 tables left join

I have 2 tables.
One like this:

uin | name

The other one like this:

tag_uin | uin_item | tagname

I want to find all the uin with the tags i want, like this:

"SELECT nir_parts.name, nir_ntag.* FROM `nir_parts`
LEFT JOIN `nir_ntag` ON nir_parts.uin = nir_ntag.uin_item 
WHERE nir_ntag.uin = 212 AND WHERE nir_ntag.uin = 313 
ORDER BY RAND() LIMIT 11"

This doesn't work for some reason... Help please.

Thanks in advance.

Either use OR to search for 2 tags or use IN()

SELECT nir_parts.name, nir_ntag.* 
FROM nir_parts 
LEFT JOIN nir_ntag ON nir_parts.uin = nir_ntag.uin_item 
WHERE nir_ntag.uin in (212, 313)
ORDER BY RAND() 
LIMIT 11

A single record can't have both tags at the same time.

If you need only records where both tags are included you can do

SELECT nir_ntag.uin_item 
FROM nir_parts 
LEFT JOIN nir_ntag ON nir_parts.uin = nir_ntag.uin_item 
WHERE nir_ntag.uin in (212, 313)
group by nir_ntag.uin_item
having count(distinct nir_ntag.uin) = 2

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