4

MySQL 是否支持公用表表达式?例如在 Oracle 中有WITH子句?:

WITH aliasname
AS
  ( SELECT COUNT(*) FROM table_name )
SELECT COUNT(*) FROM dept,aliasname
4

4 回答 4

2
SELECT t.name,
       t.num
  FROM TABLE t
  JOIN (SELECT c.id,COUNT(*) 'num1'
          FROM TABLE1 c
         WHERE c.column = 'a'
      GROUP BY c.id) ta1 ON ta1.id = t.id
 JOIN (SELECT d.id,COUNT(*) 'num2'
          FROM TABLE2 d
         WHERE d.column = 'a'
      GROUP BY d.id) ta2 ON ta2.id = t.id
于 2013-02-07T10:01:31.977 回答
1

一种方法是使用子查询:

  SELECT COUNT(*) 
  FROM dept,
  ( 
      SELECT COUNT(*) 
      FROM table_name
  ) AS aliasname

请注意,,两个表之间的交叉连接两个表与您发布的查询相同。如果它们之间有任何关系,则可以JOIN改为使用它们。

于 2013-02-07T09:56:41.270 回答
1

不,MySQL 不支持公用表表达式 (CTE)。WITH tablealias as (....)因此,您必须执行子查询,而不是使用。

例如,

WITH totalcount AS 
(select userid, count(*) as tot from logins group by userid)
SELECT a.firstname, a.lastname, b.tot
FROM users a
INNER JOIN 
totalcount b 
    on a.userid = b.userid

可以在 MySQL 中重写为

SELECT a.firstname, a.lastname, b.totalcount
FROM users a
INNER JOIN 
(select userid, count(*) as tot from logins group by userid) b 
    on a.userid = b.userid
于 2015-07-23T04:37:59.647 回答
0

所以让我们谈谈WITH从句。

WITH子句和 INNER JOIN 否则 JOIN 是一种相同的,但WITH子句给你更多的自由度,尤其是在WHERE子句中;

我将创建一个视图,该视图将获取用户数、用户名等值。

首先(创建我们的表用户和插入用户):

插入的用户表:

 CREATE TABLE users (id BIGINT(10) AUTO INCEREMENT PRIMARY KEY , name VARCHAR(50))    

用户表:

CREATE TABLE users (id BIGINT(10) AUTO INCEREMENT PRIMARY KEY , name VARCHAR(50) , gender TINYINT(1))

第二(插入一些要使用的值):

用户表:

INSERT INTO users (name,gender) VALUES ('Abolfazl M' , 1)

我不想通过查询插入到inserted_users 中,但我想添加一个TRUGGER在将数据插入到users 表之前自动将数据插入到users_inserted 表中的方法。

第三(创建触发器 add_uinserted):

DELIMITER $$


CREATE TRIGGER IF NOT EXISTS add_uinserted BEFORE INSERT ON users FOR EACH ROW 
BEGIN 

IF NEW.name <> '' THEN 

     INSERT INTO users_inserted (name) VALUES (NEW.name);

ELSE 

INSERT INTO users (name,gender) VALUES ('Unknown',NEW.gender);
INSERT INTO users_inserted (name) VALUES ('Unknown');

END IF;

END$$

DELIMITER ;

运行查询,触发器将被创建,最后让我们创建一个视图来为我们提供具有 WITH 子句的查询的结果。

CREATE VIEW select_users AS

WITH GetCAll AS (
SELECT u1.id As Uid ,COUNT(u1.name) AS CnAll FROM users u1 
)

SELECT u1.name AS NAME,CASE 
WHEN s1.gender = 1 THEN "MALE"
WHEN s1.gender = 0 THEN "FEMALE"
ELSE "UNKNOWN"
END AS GENDER,CASE 
WHEN u1.id = gca.Uid THEN "INSERTED TO users_inserted"
ELSE "NOT INSERTED TO users_inserted"
END AS INSERTED,gca.CnAll FROM GetCAll AS gca INNER JOIN users u1;

查询运行后,将创建视图,并通过调用视图select_users显示数据

最后一步(调用 select_users 视图):

SELECT * FROM select_users 

感谢您查看我的答案,就是这样!

于 2021-09-15T18:19:47.323 回答