我想使用sql查询来显示“佛罗里达”大学的“学费”和“费用”。
我使用下面的代码先查询学费,然后再结合查询第二笔费用。但是,我没有得到预期的结果。
所需的结果如下:
> School | Tuition | Fees
> --------------------------------------------
> School 1 | 2000 | 50
> School 2 | 1000 | 80
但是我得到了以下结果:
> School | Tuition | Fees
> --------------------------------------------
> School 1 | 2000 | 50
> School 1 | 1000 | 50
> School 2 | 2000 | 80
> School 2 | 1000 | 80
我对WordPress数据库使用了以下查询。 “学费”和“费用”的所有值都包含在名为“ entity_field_number”的表中。这些值在名为“值”的列中。学杂费由名为“ field_name”的列来区分。 “ entity_id”是分配给学校的ID号。
表“ entity_field_number”
> entity_id | field_name | value
> --------------------------------------------
> 1 | tuition | 2000
> 2 | tuition | 1000
> 1 | fees | 50
> 2 | fees | 80
下面是我使用的查询。
SELECT *
FROM
(SELECT field_number.`value` as tuition,
posts.`post_title` as school
FROM field_number
INNER JOIN posts
ON posts.`post_type` = 'school_dir'
AND field_number.`entity_id` = posts.`ID`
INNER JOIN field_location
ON field_location.`province` LIKE '%florida%'
AND posts.`ID` = field_location.`entity_id`
AND field_number.`field_name` = 'tuition') tuition,
(SELECT field_number.`value` as fees,
posts.`post_title` as school
FROM field_number
INNER JOIN posts
ON posts.`post_type` = 'school_dir'
AND field_number.`entity_id` = posts.`ID`
INNER JOIN field_location
ON field_location.`province` LIKE '%florida%'
AND posts.`ID` = field_location.`entity_id`
AND field_number.`field_name` = 'fees') fees
答案 0 :(得分:2)
您所做的可以这样解释...
SELECT
*
FROM
(<sql>) tuition,
(<sql>) fees
,
是CROSS JOIN
。所以你做到了...
SELECT
*
FROM
(<sql>) tuition
CROSS JOIN
(<sql>) fees
CROSS JOIN
从两个表(笛卡尔积)中获取行的每种组合。
您真正想要的是INNER JOIN
...
SELECT
*
FROM
(<sql>) tuition
INNER JOIN
(<sql>) fees
ON tuition.school = fees.school
现在,只有同一个学校的行才被加入。
但是,更好的方法是对查询进行重做以两次在field_number
表上进行联接。为此,您需要每次(以避免歧义)。
SELECT
posts.`post_title` as school,
fees.`value` as fees,
tuition.`value` as tuition
FROM
field_location
INNER JOIN
posts
ON posts.`ID` = field_location.`entity_id`
INNER JOIN
field_number AS fees
ON fees.`entity_id` = posts.`ID`
AND fees.`field_name` = 'fees'
INNER JOIN
field_number AS tuition
ON tuition.`entity_id` = posts.`ID`
AND tuition.`field_name` = 'tuition'
WHERE
field_location.`province` LIKE '%florida%'
AND posts.`post_type` = 'school_dir'