Does MySQL support common table expressions? For example in Oracle there's the WITH clause? :
WITH aliasname
AS
( SELECT COUNT(*) FROM table_name )
SELECT COUNT(*) FROM dept,aliasname
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
One way is to use a subquery:
SELECT COUNT(*)
FROM dept,
(
SELECT COUNT(*)
FROM table_name
) AS aliasname
Note that the , between the two tables will cross join the two tables the same as in your query you posted. IF there is any relation between them you can JOIN them instead.
No, MySQL does not support Common Table Expressions (CTE). So instead of using WITH tablealias as (....), you will have to do a subquery.
For example,
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
can be re-written in MySQL as
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
So let's talk about WITH clause .
WITH clause and INNER JOIN otherwise JOIN are a kind of same , but WITH clause gives you much more latitude especially in WHERE clause ;
I am going to make a view that'll get values like count of users , user name and etc.
First (Creating our tables users and inserted_users) :
inserted_users table :
CREATE TABLE users (id BIGINT(10) AUTO INCEREMENT PRIMARY KEY , name VARCHAR(50))
users table :
CREATE TABLE users (id BIGINT(10) AUTO INCEREMENT PRIMARY KEY , name VARCHAR(50) , gender TINYINT(1))
Second (Inserting some values to work with) :
users table :
INSERT INTO users (name,gender) VALUES ('Abolfazl M' , 1)
I don't want to insert into inserted_users by query , but I want to add a TRUGGER which will insert data automatically to users_inserted table before data be inserted into users table.
Third (Creating trigger 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 ;
Run the query and the trigger will be created and at last let's create a view to give us result from a query having WITH clause .
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;
After you query got ran the view will be created and by calling the view select_users the data will be shown
Last step (calling the select_users view) :
SELECT * FROM select_users
Thanks for taking a look at my answer , and that's it !!
Related
This question already has an answer here:
Get all records in first tbl and matching in second tbl (indicating ones that existed)
(1 answer)
Closed 6 years ago.
i have two tables users and manager.
My tables are like this:
Use this
select user.id,user.name,case when(project.id is null) then 'No' else 'yes'end has_project from user left outer join project on project.user_id = user.id
At the moment Im not available mysql server, but wrote example on mysql, might fit for you.
create table
UserTable
(
id integer,
name text
);
insert into UserTable select 1, 'abc';
insert into UserTable select 2, 'def';
insert into UserTable select 3, 'ghi';
select
*
from
UserTable;
create table
ProjectTable
(
id ineger,
user_id integer
);
insert into ProjectTable select 1, 2;
insert into ProjectTable select 2, 1;
insert into ProjectTable select 3, 1;
select
*
from
ProjectTable;
select
u.id,
u.name,
case
when p.id not null then 'Yes'
else 'No'
end 'HasProject'
from
UserTable u
left join
ProjectTable p
on
u.id = p.user_id
group by
u.id;
I want to insert into the last column (number of people in that room) and
I want to use
insert into table(n_people_in_room)
select count(people_id)
from table
group by room
This is obvious wrong because i need to join the table with itself on people_id but i didn't. What is the right code?
Here's one way to do it, using an inline view to get the N_People_In_Room totals:
I'd do it as a SELECT first:
SELECT t.peopleid
, t.room
, t.n_people_in_room AS `old_npir`
, s.n_people_in_room AS `new_npir`
FROM mytable t
JOIN ( SELECT c.room
, COUNT(1) AS n_people_in_room
FROM mytable c
GROUP BY c.room
) s
ON s.room = t.room
Convert that into an UPDATE by repacing SELECT ... FROM with UPDATE, and adding a SET clause...
UPDATE mytable t
JOIN ( SELECT c.room
, COUNT(1) AS n_people_in_room
FROM mytable c
GROUP BY c.room
) s
ON s.room = t.room
SET t.n_people_in_room = s.n_people_in_room
I'm attempting to update a MySQL table to show column name 'processed' as '2' if there is duplicate entries for 'name' and 'address_1', but it's not working - as usual I think I'm just being a bit of a moron..
Here's what I'm trying
UPDATE `records`
SET `processed`='2', `count` = (SELECT COUNT(`user`)
FROM `records`
WHERE `name`<>''
AND `address_1`<>'')
WHERE `count`=> '1';
Basically, if there's more than one 'name' and 'address_1' then the 'processed' field needs updating to '2'..
You could use a query like this one to return duplicated names and addresses:
SELECT name, address_1, COUNT(*) cnt
FROM records
GROUP BY name, address_1
HAVING COUNT(*)>1
and then join this query to the records table, and update the column processed to 2 where the join succeeds:
UPDATE
records INNER JOIN (SELECT name, address_1, COUNT(*) cnt
FROM records
GROUP BY name, address_1
HAVING COUNT(*)>1) duplicates
ON records.name = duplicates.name
AND records.address_1=duplicates.address_1
SET
`processed`='2',
`count` = duplicates.cnt
WHERE
records.`name`<>''
AND records.`address_1`<>''
In my system I want to get attendance data of employee from the DB, so I wrote a huge SQL query, and it gives me relevant details. But now I need an updated version of particular results. So I don’t know how to put this query within the update statement.
select * from(
select concat('pre:', date) as date,concat('pre:',employee_no) as employee_no,concat('pre:',name_with_initials) as name,concat('pre:',sign_in_at) as sign_in_at,concat('pre:',sign_out_at) as sign_out_at,emp from( SELECT date, present.employee_no,employee_details.name_with_initials,present.sign_in_at, present.sign_out_at,employee_details.employee_no as emp from (
SELECT employee_no,date,sign_in_at,sign_out_at FROM complete_shifts WHERE date = '2013-06-17' UNION ALL
SELECT employee_no,date,sign_in_at,'00:00:00 ' AS sign_out_at FROM incomplete_shifts WHERE date = '2013-06-17' UNION ALL
SELECT employee_no,date,sign_in_at,'00:00:00 ' AS sign_out_at FROM incomplete_shift_records WHERE date = '2013-06-17'
)as present inner join employee_details on present.employee_no = employee_details.employee_no
) as final_present
union all
select concat('ab:',date)as date,concat('ab:',employee_no)as employee_no,concat('ab:',name_with_initials)as name,concat('ab:',sign_in_at)as sign_in_at,concat('ab:',sign_out_at)as sign_out_at, emp from(
select '2013-06-17' AS date,absent.employee_no,employee_details.name_with_initials,'00:00:00'as sign_in_at , '00:00:00' as sign_out_at,employee_details.employee_no as emp from (
select * from ( SELECT employee_details.employee_no FROM employee_details left outer join resigned_emps on
employee_details.employee_no = resigned_emps.employee_no where resigned_emps.date is null or resigned_emps.date>'2013-06-17'
) as available_emps left outer join (
select employee_no from complete_shifts where date = '2013-06-17' union
select employee_no from incomplete_shifts where date = '2013-06-17' union
select employee_no from incomplete_shift_records where date = '2013-06-17'
) as present on available_emps.employee_no = present.employee_no where present.employee_no is null
) as absent inner join employee_details on absent.employee_no = employee_details.employee_no
) as final_absent
)as final left outer join( SELECT leave.employee_no as lv_emp
FROM leave_dates inner join leave on leave_dates.leave_id = leave.leave_id where leave_dates.date = '2013-06-17')as leave_emps
on final.emp = leave_emps.lv_emp;
With such a large query, you should just put the results in a temporary table and update from that.
create temporary table toupdate as
<your query goes here>;
Now you can investigate the data that will be updated, to be sure that it really is ok.
Next you can do the update as a join:
update table_to_update t join
toupdate
on t.key = toupdate.key
set t.col = toupdate.col
Because you don't give the column or table details, this is just the structure of such a solution.
Instead of "select *", use the appropriate unique field to fetch the records to update, ex EmpID. Finally use this result as inner query result to update query.
Example
Update ... set ... where empid in (your select query goes here)
I'm trying to get an id from a companies table where the id is not yet in the crawlLog table. Then I need to insert that companyId into the crawlLog table.
I need to do this in one call so that parallel crawlers don't pull the same url after some other crawler has selected a url, but hasn't inserted it into the crawl log yet. I don't want to lock tables because of other problems that generates.
I get this error from both queries below:
You can't specify target table 'crawlLog' for update in FROM clause
Here are two queries i've tried to do the same thing.
INSERT INTO crawlLog (companyId, timeStartCrawling)
VALUES
(
(
SELECT companies.id FROM companies
LEFT OUTER JOIN crawlLog
ON companies.id = crawlLog.companyId
WHERE crawlLog.companyId IS NULL
LIMIT 1
),
now()
)
I've also tried this, but get the same error:
INSERT INTO crawlLog (companyId, timeStartCrawling)
VALUES
(
(
SELECT id
FROM companies
WHERE id NOT IN
(
SELECT companyId
FROM crawlLog
)
LIMIT 1
),
now()
)
Why use a Subselect? INSERT INTO ... SELECT exists:
INSERT INTO crawlLog (companyId, timeStartCrawling)
SELECT companies.id, NOW()
FROM companies
LEFT OUTER JOIN crawlLog
ON companies.id = crawlLog.companyId
WHERE crawlLog.companyId IS NULL
LIMIT 1
And that way it should not complain about using a table both in the INSERT and SELECT part
You can't update rows which you are querying. There is a way to force MySQL to use a temporary table implicitly:
INSERT INTO crawlLog (companyId, timeStartCrawling)
VALUES
(
SELECT id, when FROM
(
SELECT companies.id AS id, now() AS when FROM companies
LEFT OUTER JOIN crawlLog
ON companies.id = crawlLog.companyId
WHERE crawlLog.companyId IS NULL
LIMIT 1
)
)
This works and seems like the simplest solution:
Using the simpler of the two statements in my question, I created an alias for the inner crawlLog table as suggested by #Tocco in the comments, and then removed the necessary encapsulation in VALUES().
INSERT INTO crawlLog (companyId, timeStartCrawling)
SELECT id, now()
FROM companies
WHERE id NOT IN
(
SELECT companyId
FROM crawlLog AS crawlLogAlias
)
LIMIT 1
Do the select into a temp table, then insert selecting from the temp table. You can't insert into a table and select from it in the same statement, so use a temp table and two statements.