How to chain where and where not in in sql? - sql

I have these two queries working:
var queryOne = client.query("SELECT * FROM tableone WHERE (tableone.id) NOT
IN ( SELECT tabletwo.id FROM tabletwo)");
var queryTwo = client.query("SELECT * FROM tableone WHERE time = 1")
I am attempting to combine them into one query:
var finalQuery = client.query("SELECT * FROM tableone WHERE time = 1 AND
WHERE (tableone.id) NOT IN ( SELECT tabletwo.id FROM tabletwo)");
However, I am running into this error: syntax error at or near "WHERE"
How can I correctly, combine the two queries?

drop the second WHERE, it's not needed:
var finalQuery = client.query("SELECT * FROM tableone WHERE time = 1 AND
(tableone.id) NOT IN ( SELECT tabletwo.id FROM tabletwo)");

Related

how to convert postgres query looking for records where value appears only once to knex

I am trying to convert a postgres valid query that returns what I require to a knex query...
I keep getting various errors and can't write the knex query properly.
I have several versions of the query in postgres to find records in a table that appear only once and that have a specific user_id.
here are the different variants:
select * from project_authors t1
where (select count(*) from project_authors t2
where t1.project_id = t2.project_id) = 1
AND t1.user_id=2
OR
select * from project_authors t1
where NOT exists
(select 1 from project_authors t2
where t1.project_id = t2.project_id and t1.user_id <> t2.user_id) AND t1.user_id=2
OR
select * from project_authors t1
INNER JOIN (SELECT t3.project_id FROM project_authors t3 GROUP BY t3.project_id
HAVING COUNT (t3.project_id)=1) t2
ON t1.project_id=t2.project_id Where t1.user_id=2
the way I write the knex query is using parameters supplied in the request (for example):
const _readDbSingleAuthor = (table1, column1, criteria) => {
return db(`${table1} as t1`)
.select("*")
.where(
db(`${table1} as t2`)
.select("*")
.count("*")
.where(`t1.${column1}`, "=", `t2.${column1}`),
"=",
1
)
.andWhere(criteria);
I would appreciate any help...
the version above gave me a "maximum call stack exceeded" - so I hit the stackoverflow literally.
a version using join was the closest thing but gave me a result saying that the project_id column was ambiguous:
const _readDbSingleAuthor = (table1, data, column1, criteria) => {
return db
.select(data)
.from(`${table1} as t1`)
.join(
db
.select(column1)
.from(`${table1} as t3`)
.count(`${column1} as count`)
.groupBy(column1)
.having("t3.count", "=", 1)
.as("t2"),
`t2.${column1}`,
"=",
`t1.${column1}`
)
.where(criteria);
};

how to delete the results of a complex query

When I replace select * with delete I get a syntax error on line 2 near t. But I need that t, because I'm referencing it in the where clause. So how do I delete the results of this query?
select *
from [PrimusGroup].[dbo].[PrmsBlotter] t
where t.RunType = 'Backtesting'
and not exists (
select 1
from [PrimusGroup].[dbo].[PrmsBlotter] i
where i.RunType = 'Live'
and i.BBox = t.BBox
and convert(date,i.RunDateStart) = convert(date,t.TestDateFrom)
)
As #Gordon Linoff said, replace the select * with delete t.
delete t
from [PrimusGroup].[dbo].[PrmsBlotter] t
where t.RunType = 'Backtesting'
and not exists (
select 1
from [PrimusGroup].[dbo].[PrmsBlotter] i
where i.RunType = 'Live'
and i.BBox = t.BBox
and convert(date,i.RunDateStart) = convert(date,t.TestDateFrom)
)

Combine two different select statements, one distinct the other not

I have two selects which are required to filter data. They are not complicated:
"SELECT * FROM StevesTable t WHERE "
"t.data1 = '%s' AND "
"t.data2 = to_date('%s','DD/MM/YYYY');",
strdata1,
dtDate.Format();
and
SELECT distinct data1 FROM anothertable ftt
join table1 tab on tab.somedata = ftt.somedata
where tab.somedata = 0
and tab.someotherdata = 1
I would like to combine these two as I need to filter the returned dataset from the first select statement by the returned field in the second (ie if a record returned in the first set does not have a data1 value which is contained in the second returned set it is invalid).
I tried to union and intersect the selects but you need the same number of columns returned and that cannot happen as these are completely different tables. When I tried to simply merge them together I found it difficult as the second select statement is a distinct select whereas the first is not.
I was wondering whether I had missed a trick somewhere for combining these sorts of selects?
What you need is a SQL sub-query:
SELECT * FROM StevesTable t
WHERE t.data1 = '%s'
AND t.data2 = to_date('%s','DD/MM/YYYY')
AND t.data1 in (select distinct data1 FROM anothertable ftt
join table1 tab on tab.somedata = ftt.somedata
where tab.somedata = 0
and tab.someotherdata = 1)
There, you check that all records in the first select have a data1 value in the second set.
You can do this using an EXISTS condition:
SELECT * FROM StevesTable t
WHERE t.data1 = '%s' AND
t.data2 = to_date('%s','DD/MM/YYYY') AND
EXISTS (select null
from anothertable ftt
join table1 tab on tab.somedata = ftt.somedata
where tab.somedata = 0 and
tab.someotherdata = 1 and
ftt.data1 = t.data1)

php sql merge 2 queries

I have 2 queries one straight after the other:
$sql_result8 = mysql_query("SELECT * FROM properties WHERE c4='$id'", $db); $charges = mysql_num_rows($sql_result8);
$sql_result8 = mysql_query("SELECT * FROM vehicles WHERE c4='$id'", $db); $charges = $charges + mysql_num_rows($sql_result8);
What kind of query would I need to merge these? Some kind of JOIN? UNION?
SELECT * FROM properties p, vehicles v WHERE p.c4 = v.c4 AND p.c4 = '$id'
Try this
SELECT * FROM properties JOIN vehicles USING (c4) WHERE c4='$id'
If you want to just find out the number or rows returned from both queries and not show the actual columns, you can use this:
$sql_result8 = mysql_query(
"SELECT
( SELECT COUNT(*) FROM properties WHERE c4='$id' )
+ ( SELECT COUNT(*) FROM vehicles WHERE c4='$id' )
", $db );

MySQL subquery returns more than one row

I am executing this query:
SELECT
voterfile_county.Name,
voterfile_precienct.PREC_ID,
voterfile_precienct.Name,
COUNT((SELECT voterfile_voter.ID
FROM voterfile_voter
JOIN voterfile_household
WHERE voterfile_voter.House_ID = voterfile_household.ID
AND voterfile_household.Precnum = voterfile_precienct.PREC_ID)) AS Voters
FROM voterfile_precienct JOIN voterfile_county
WHERE voterfile_precienct.County_ID = voterfile_County.ID;
I am trying to make it return something like this:
County_Name Prec_ID Prec_Name Voters(Count of # of voters in that precienct)
However, I am getting the error:
#1242 - Subquery returns more than 1 row.
I have tried placing the COUNT statement in the subquery but I get an invalid syntax error.
If you get error:error no 1242 Subquery returns more than one row, try to put ANY before your subquery. Eg:
This query return error:
SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);
This is good query:
SELECT * FROM t1 WHERE column1 = ANY (SELECT column1 FROM t2);
You can try it without the subquery, with a simple group by:
SELECT voterfile_county.Name,
voterfile_precienct.PREC_ID,
voterfile_precienct.Name,
count(voterfile_voter.ID)
FROM voterfile_county
JOIN voterfile_precienct
ON voterfile_precienct.County_ID = voterfile_County.ID
JOIN voterfile_household
ON voterfile_household.Precnum = voterfile_precienct.PREC_ID
JOIN voterfile_voter
ON voterfile_voter.House_ID = voterfile_household.ID
GROUP BY voterfile_county.Name,
voterfile_precienct.PREC_ID,
voterfile_precienct.Name
When you use GROUP BY, any column that you are not grouping on must have an aggregate clause (f.e. SUM or COUNT.) So in this case you have to group on county name, precienct.id and precient.name.
Try this
SELECT
voterfile_county.Name, voterfile_precienct.PREC_ID,
voterfile_precienct.Name,
(SELECT COUNT(voterfile_voter.ID)
FROM voterfile_voter JOIN voterfile_household
WHERE voterfile_voter.House_ID = voterfile_household.ID
AND voterfile_household.Precnum = voterfile_precienct.PREC_ID) as Voters
FROM voterfile_precienct JOIN voterfile_county
ON voterfile_precienct.County_ID = voterfile_County.ID
See the below example and modify your query accordingly.
select COUNT(ResultTPLAlias.id) from
(select id from Table_name where .... ) ResultTPLAlias;