使用PHP和MySQL从多个表的多个列中选择DISTINCT
使用PHP和MySQL,我试图从下面列出的所有4个表的数字和类型列中获取所有不同的值:使用PHP和MySQL从多个表的多个列中选择DISTINCT,php,mysql,distinct,Php,Mysql,Distinct,使用PHP和MySQL,我试图从下面列出的所有4个表的数字和类型列中获取所有不同的值: table_1 ID|t1_number|t1_type 1|1|new 2|1|old 3|2|new 4|3|new 5|1|old table_2 ID|t2_number|t2_type 1|1|future 2|1|new 3|3|past 4|3|new 5|1|new table_3 ID|t3_number|t3_type 1|1|past 2|1|new 3|1|new 4|1|n
table_1
ID|t1_number|t1_type
1|1|new
2|1|old
3|2|new
4|3|new
5|1|old
table_2
ID|t2_number|t2_type
1|1|future
2|1|new
3|3|past
4|3|new
5|1|new
table_3
ID|t3_number|t3_type
1|1|past
2|1|new
3|1|new
4|1|new
5|1|old
table_4
ID|t4_number|t4_type
1|1|new
2|4|new
3|3|old
4|2|new
5|1|new
我希望从上表中得到的值为:
数字:1,2,3,4
类型:新、旧、未来、过去
这是我到目前为止所拥有的;但我不确定SQL是否正确,也不确定如何格式化while循环以获取值
$sql = "SELECT DISTINCT table_1.t1_number, table_2.t2_number, table_3.t3_number, table_4.t4_number, table_1.t1_type, table_2.t2_type, table_3.t3_type, table_4.t4_type
FROM table_1
JOIN table_2
JOIN table_3
JOIN table_4";
$result = @mysql_query($sql, $con) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$numbers= $row[?????????];
}
使用SQL:
SELECT DISTINCT t1_number AS num FROM t1
WHERE num NOT IN (SELECT t2_number FROM t2)
AND num NOT IN (SELECT t3_number FROM t3)
AND num NOT IN (SELECT t4_number FROM t4)
同样的想法也适用于这些类型。你想要什么还不完全清楚。你想要四个不同的数字,然后是四个不同的类型吗
SELECT t1_number FROM table_1
UNION SELECT t2_number FROM table_2
UNION SELECT t3_number FROM table_3
UNION SELECT t4_number FROM table_4;
SELECT t1_type FROM table_1
UNION SELECT t2_type FROM table_2
UNION SELECT t3_type FROM table_3
UNION SELECT t4_type FROM table_4;
或者您想要每一对不同的数字和类型
SELECT t1_number, t1_type FROM table_1
UNION SELECT t2_number, t2_type FROM table_2
UNION SELECT t3_number, t3_type FROM table_3
UNION SELECT t4_number, t4_type FROM table_4;
UNION的一个优点是它隐式地将结果减少到不同的行。如果使用UNION ALL,则可以保留重复项。在单个查询中执行此操作可能会在输出中复制数字或类型列的值,如果一个列表的值多于另一个列表的值。要为任一列获取不同的值列表,需要进行单独的查询: 数 类型
在这个联合查询中运行DISTINCT没有任何价值,因为重复项将被删除,而这只处理一列。我想这就是您想要的:
select distinct number_value, type_value from (
select t1_number as number_value, t1_type as type_value from table_1
union
select t2_number as number_value, t2_type as type_value from table_2
union
select t3_number as number_value, t3_type as type_value from table_3
union
select t4_number as number_value, t4_type as type_value from table_4
)
@马克·拜尔斯:你的意思是他可以从规范化他的数据库中获益。@Bill Karwin:哦,是的,这就是我的意思。:)这将只返回来自
表1 t1的值;它不会有其他表中不存在的值,表1和表2的不同列号如何?
SELECT t1_type AS type
FROM TABLE_1
UNION
SELECT t2_type
FROM TABLE_2
UNION
SELECT t3_type
FROM TABLE_3
UNION
SELECT t4_type
FROM TABLE_4
select distinct number_value, type_value from (
select t1_number as number_value, t1_type as type_value from table_1
union
select t2_number as number_value, t2_type as type_value from table_2
union
select t3_number as number_value, t3_type as type_value from table_3
union
select t4_number as number_value, t4_type as type_value from table_4
)