MySQL从表中选择名称,将属性与相关表进行比较

时间:2016-07-27 11:54:05

标签: mysql sql

表1

customer_name       restaurant_id         visits
shubham              1                     4
nayan                2                     6 

表2

restaurant_id       restaurant_name
  1                       ramon hux
  2                       Mt.Pete's

问题:打印访问次数超过3的客户的姓名,餐馆名称应该是空格还是单引号?

我的回答:

select customer_name from table1 where id=(select id from table2 
where restaurant_name like "% %" or restaurant_name like "%'%") and visits>3;

问题:子查询返回超过1行;

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

尝试使用IN子句:

select customer_name from table1 where id IN (select id from table2 
where restaurant_name like "% %" or restaurant_name like "%'%") and visits>3;

您的子查询返回的ID超过1,因此您的查询失败。您需要使用IN来合并所有ID。

答案 1 :(得分:2)

您可以使用JOIN

代替子查询,而不是使用子查询
SELECT T1.customer_name 
FROM table1 T1
JOIN table2 T2 ON T2.id = T1.id
WHERE T1.visits > 3 AND (T2.restaurant_name LIKE "% %" OR T2.restaurant_name LIKE "%'%")