繁体   English   中英

通过php与mysql比较两个表

[英]Compare two tables with mysql through php

说我有这两个mysql表:

country
----
username        Country
John            USA
Sarah           Canada
fav_color
----
username        Color
John            Blue
Sarah           Green

如何选择Sarah最喜欢的颜色,但仅限于她在加拿大的情况下?

就像是:

SELECT color FROM fav_color WHERE name='sarah' AND username=(a canadian username)

一个相当简单的JOIN;

SELECT color FROM fav_color f
JOIN country c ON c.username=f.username
WHERE c.username='Sarah'
  AND c.country='Canada';

演示在这里

在两个表上选择,然后指定要按用户名匹配记录:

SELECT color FROM fav_color, country 
    WHERE fav_color.username='Sarah' AND
    fav_color.username = country.username AND
    country = 'Canada';

使用WHERE EXISTS怎么样?

SELECT color FROM fav_color
    WHERE EXISTS
        (SELECT username FROM country
             WHERE country.username = fav_color.username
             AND country.Country = 'Canada')
select color from fav_color where 
    name='sarah' and 
    name in (
        select name from country where country='canada'
    )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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