Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
具有左外联接和平均值的mysql查询_Mysql_Sql - Fatal编程技术网

具有左外联接和平均值的mysql查询

具有左外联接和平均值的mysql查询,mysql,sql,Mysql,Sql,我在mysql中有两个表。第一个表是名称,日期如下: name service number carlos telephone 6 juan watter 12 maria gas 23 jhon hostal 17 marcos

我在mysql中有两个表。第一个表是名称,日期如下:

    name           service         number
    carlos          telephone         6
    juan             watter          12
    maria             gas            23
    jhon             hostal          17
    marcos           sleeping        21
    carlos          othercarlos      12
    other             other          13
我还有另一个表别名

    name             service         alias              price
   carlos          telephone        telephone-carlos     700
   carlos          sleeping         sleeping-carlos      300  
    juan             watter          watter-juan         900
    maria             gas            gas-maria           650
    jhon             hostal          hostal-jhon         700
我需要一个有名字,别名,号码和王子的视图。 但我需要名称中的所有行,我打算使用左外部联接。 但问题是,当我查询when is other carlos时,我需要的是carlos服务的平均价格,当名称为other时,我需要的是所有服务的平均价格。但似乎无效


我创建这个表和我的查询

好的,我确信有更好的方法可以做到这一点,但我至少可以为您提供一种方法:

SELECT  t1.name, 
        t1.service, 
        t2.alias, 
        t1.number, 
        COALESCE(t2.price,t3.price,t4.price) AS price
FROM name t1
LEFT JOIN alias t2
    ON t1.name= t2.name 
    AND t1.service = t2.service
LEFT JOIN ( SELECT name, AVG(price) AS price
            FROM alias
            GROUP BY name) t3
    ON t1.name = t3.name
LEFT JOIN ( SELECT AVG(price) AS price
            FROM alias) t4
    ON t1.name = 'other'
用这个

结果是:

╔════════╦═════════════╦══════════════════╦════════╦═══════╗
║  NAME  ║   SERVICE   ║      ALIAS       ║ NUMBER ║ PRICE ║
╠════════╬═════════════╬══════════════════╬════════╬═══════╣
║ carlos ║ telephone   ║ telephone-carlos ║      6 ║   700 ║
║ juan   ║ watter      ║ watter-juan      ║     12 ║   900 ║
║ maria  ║ gas         ║ gas-maria        ║     15 ║   250 ║
║ jhon   ║ hostal      ║ hostal-jhon      ║     21 ║   640 ║
║ carlos ║ sleeping    ║ sleeping-carlos  ║     24 ║   300 ║
║ carlos ║ othercarlos ║ (null)           ║     11 ║   500 ║
║ other  ║ (null)      ║ (null)           ║      2 ║   558 ║
╚════════╩═════════════╩══════════════════╩════════╩═══════╝

出色的工作,包括小提琴!不过我还是不太明白这个问题。你能把输出包括进来吗?你能把想要的结果公布出来吗?