使用两个表中的条件从MySQL表中选择数据

时间:2014-05-13 06:37:39

标签: mysql sql database

我有两个MySQL表HouseHold和UserProfile。两个表都包含HouseHoldID列。我想从HouseHold Table中选择两个表中HouseHoldID相等的所有行。我怎样才能做到这一点?我使用以下代码

select * from Household where Household.HouseholdID = UserProfile.HouseholdID

但它没有给出任何反映错误的东西。 任何人都可以帮助我吗?

6 个答案:

答案 0 :(得分:1)

你必须从两个表中选择
喜欢以下方式:

select * from Household, UserProfile where Household.HouseholdID = UserProfile.HouseholdID

或使用加入

select * from Household h
JOIN UserProfile u
ON u.HouseholdID=h.HouseholdID

答案 1 :(得分:0)

您还需要选择UserProfile表

select * from Household h JOIN UserProfile u ON h.HouseholdID = u.HouseholdID

答案 2 :(得分:0)

您可以尝试:

SELECT A.* FROM Household A INNER JOIN UserProfile B ON A.HouseholdID = B.HouseholdID

答案 3 :(得分:0)

您可以使用JOIN

select * from Household
JOIN UserProfile
ON UserProfile.HouseholdID=Household.HouseholdID

或使用EXISTS

select * from Household
WHERE EXISTS
(
   SELECT NULL
   FROM UserProfile
   WHERE UserProfile.HouseholdID=Household.HouseholdID
)

或使用IN

select * from Household
WHERE Household.HouseholdID IN 
(
   SELECT UserProfile.HouseholdID
   FROM UserProfile
)

或者使用from语句的旧方法

select * from Household, UserProfile
WHERE UserProfile.HouseholdID=Household.HouseholdID

这有点取决于您想要的数据

答案 4 :(得分:0)

您需要JOIN表格。试试这个:

select * from 
Household h JOIN
UserProfile u ON u.HouseholdID =h.HouseholdID 

详细了解加入here

答案 5 :(得分:0)

那么,SQL语言有非常巧妙的方法可以按照给定的标准从两个表中选择记录,它被称为 JOIN

SELECT H.*, U.* FROM Household H 
INNER JOIN UserProfile U ON U.HouseholdID = H.HouseholdID