我正在查询产生所需结果的两个表。我需要从这个结果数组中有条件地插入元素到另一个表中。请原谅我缺乏理解,但我对php和mysql相当新。
结果字段为:bus_id, age, race, and sex
。我想有条件地将这些字段的元素插入到另一个包含字段的表中:bus_id, no_people, males, females, and ethnicity%
。
结果数组中的bus_id
确实=插入表格中的bus_id
。
例如,我想计算分配给特定bus_id
的人数,并确定人数,男性,女性和种族百分比。
我的思维过程可能看似令人费解,但请原谅我是一个新手。如果你能把我放在正确的方向,我们将不胜感激。
好的,这是我对前两张表的查询结果表:
bus_name bus_id cus_name age race sex DHL 10 tom selleck 32 asian male Fedex 17 jennifer lopez 34 black female UPS 1 jet li 26 black male UPS 1 hugh douglas 40 black male UPS 1 ray lewis 40 white male UPS 1 michael vick 38 black male UPS 1 ed reed 44 white male UPS 1 joe flacco 17 white male UPS 1 bob dole 26 latin male UPS 1 deion sanders 15 white male UPS 1 bill clinton 15 latin male UPS 1 lebron james 41 white male
我想在另一个名为“comp_struct”的表中有条件地插入这些元素,其中包含以下字段:bus_id,males,female,ethnicity%(可能会将其更改为多样性百分比)忘记现在的种族%。
所以我希望它在完成后看起来像这样。
bus_id no_people males females 1 10 10 0 17 1 0 1 10 1 1 0
这是我用我的代码创建第一个表结果的程度。
$query1 = $db->query("SELECT bus.bus_name, bus.bus_id, bus_users.purch, bus_users.cus_name, bus_users.age, bus_users.race, bus_users.sex FROM bus, bus_users WHERE bus_users.purch = bus.bus_id ORDER BY bus.bus_name") or die($db->error); while($result = mysqli_fetch_assoc($query1)) { ( "SELECT bus_id, COUNT(*), SUM(IF(sex='male', 1, 0)) AS males, SUM(IF(sex='female', 1, 0)) AS females FROM @query1 GROUP BY bus_id INSERT INTO comp_struct (bus_id, no_people, males, females) SELECT bus_id, COUNT(*) AS no_people, SUM(IF(sex='male', 1, 0)) AS males, SUM(IF(sex='female', 1, 0)) AS females FROM @query1 GROUP BY bus_id");
毋庸置疑,这并没有产生预期的效果。
答案 0 :(得分:0)
暂时忽略种族字段,您可以获得所需的值: -
SELECT bus_id,
COUNT(*),
SUM(IF(sex='male', 1, 0)) AS males,
SUM(IF(sex='female', 1, 0)) AS females
FROM table_one
GROUP BY bus_id
并插入: -
INSERT INTO table_two(bus_id, no_people, males, females)
SELECT bus_id,
COUNT(*) AS no_people,
SUM(IF(sex='male', 1, 0)) AS males,
SUM(IF(sex='female', 1, 0)) AS females
FROM table_one
GROUP BY bus_id
编辑 - 基于您现在给出的详细信息,单个语句将按如下方式执行插入(无需先单独选择行)
INSERT INTO table_two(bus_id, no_people, males, females)
SELECT bus.bus_id ,
COUNT(*) AS no_people,
SUM(IF(bus_users.sex ='male', 1, 0)) AS males,
SUM(IF(bus_users.sex ='female', 1, 0)) AS females
FROM bus
INNER JOIN bus_users
ON bus_users.purch = bus.bus_id
GROUP BY bus.bus_id
编辑 - 这也可以让你获得种族: -
SELECT bus_id, no_people, males, females, GROUP_CONCAT(CONCAT(race, race_percentage, '%'))
FROM
(
SELECT Sub1.bus_id, Sub2.no_people, Sub2.males, Sub2.females, Sub1.race, (Sub1.race_count / Sub2.no_people) * 100 AS race_percentage
FROM
(
SELECT bus.bus_id ,
bus_users.race,
COUNT(*) AS race_count
FROM bus
INNER JOIN bus_users
ON bus_users.purch = bus.bus_id
GROUP BY bus.bus_id, race
) Sub1
INNER JOIN
(
SELECT bus.bus_id ,
COUNT(*) AS no_people,
SUM(IF(bus_users.sex ='male', 1, 0)) AS males,
SUM(IF(bus_users.sex ='female', 1, 0)) AS females
FROM bus
INNER JOIN bus_users
ON bus_users.purch = bus.bus_id
GROUP BY bus.bus_id
) Sub2
ON Sub1.bus_id = Sub2.bus_id
) Sub0
GROUP BY bus_id
SQL在这里小提琴: -