yii active record NOT IN query - yii

How can we implement CActive Record for this query in yii
SELECT *
FROM location WHERE locationid NOT IN
( SELECT location
FROM memberlocation
WHERE memberid = 2371)

Try this
$sql='SELECT *
FROM location WHERE locationid NOT IN
( SELECT location
FROM memberlocation
WHERE memberid = 2371)';
$result = Yii::app()->db->createCommand($sql)->queryAll();
Or you could do something like this
$result= Location::model()->findAll(array(
'select'=>'*',
'condition'=>'locationid NOT IN( SELECT location
FROM memberlocation
WHERE memberid = :member_id)',
'params'=>array(':member_id'=2371)
));

Related

How to update a table from a select query

i am creating a temp table using DB facade and then using select query i need to update some columns in temp table based on condition
DB::update('update table_temp_topcustomer
set ordercount = aaa.ordercount
from
(select count(id) as ordercount,mobileno
from order_hdrs
group by mobileno
) as aaa
where table_temp_topcustomer .mobileno = aaa.mobileno
');
it gives this error
Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'from (select count(id) as ordercount,mobileno from order_hdrs group by mobileno ' at line 1 (SQL: update table_temp_topcustomer set ordercount = aaa.ordercount from (select count(id) as ordercount,mobileno from order_hdrs group by mobileno ) as aaa )
How can i achieve this?
UPDATE table_temp_topcustomer JOIN
( SELECT order_hdrs count(*) as ordercount
FROM order_hdrs
GROUP BY mobileno
) AS aaa
ON table_temp_topcustomer.mobileno = aaa.mobileno
SET table_temp_topcustomer.ordercount = aaa.ordercount
I guess you can't do in single query. As per my understanding. First get the select result and in loop do update.
You should try something like below.
$result = DB::select('select count(id) as ordercount,mobileno
from order_hdrs
group by mobileno');
foreach($result as $item) {
DB::update('update table_temp_topcustomer
set ordercount = '. $item->ordercount .'
where table_temp_topcustomer.mobileno = ' $item->mobileno);
}

How to append rows to result from SELECT query in SQL?

I have a query which gives me desired result. Column names are like this(which I am getting from the query):
RXID |DrName |SBOID |SBOName |RxHonoredDate |RxnHonoured |CallRecievedFrom |MobileNo
Now I have one table named 'SampleRepeat'. This have following columns
DrID | CallRecievedFrom | Mobile | SBOID |RxnHonoured
(Here we'll fetch DrName through DrID from table TblDr and SBOName through SBOID)
This is my query:
select G.RXID, NoOfRx, DrName,HospitalName,G.EmpCode AS SBOID ,TM_Name AS SBOName,CONVERT(DATETIME,H.CreatedDate) AS RxHonoredDate, DrSpeciality AS Speciality,
convert(DATETIME, G.CreatedDate) AS [RxGeneratedDate],COALESCE(H.rows, 0) AS RxnHonoured,
CallRecievedFrom,MobileNo ,G.HQ
from(
select RXID,SUM(RxGenerate) as NoOfRx, DrName,HospitalName,RX.EmpCode,TE.TM_Name, DrSpeciality,convert(DATE,RX.CreatedDate)as CreatedDate,TE.Territory AS HQ
from tbl_rx RX
left join tblEmployee TE on TE.TM_Emp_Id=RX.EmpCode
GROUP BY RX.EmpCode,RX.DrName,RX.HospitalName,RX.CreatedDate,RX.DrSpeciality,TE.TM_Name,RX.RXID,TE.Territory
)G
left join
( SELECT EmpCode,DrID,CreatedDate, SUM(MedToPCount) AS rows,CallRecievedFrom,MobileNo FROM tbl_MedicinToPatient WHERE Status = 'Delivered' GROUP BY EmpCode,DrID,CreatedDate,CallRecievedFrom,MobileNo
)H
on H.DrID=G.RXID ORDER BY TM_Name, H.CreatedDate ASC
I want to append this table values to end of query result and all other columns will be null.
I have tried Union all but no success. How do I do that? Any help would be much appreciated.
UNION with a calculated column or UNION ALL should work.
SELECT
*
FROM
(
SELECT
OrderID = 1
RXID,
DrName,
SBOID,
SBOName,
RxHonoredDate,
RxnHonoured,
CallRecievedFrom,
MobileNo
FROM
Query Q
UNION
SELECT
OrderID = 2
RXID = NULL,
DrName = DrID,
SBOID = NULL,
SBOName = SBOID,
RxHonoredDate = NULL,
RxnHonoured,
CallRecievedFrom,
MobileNo = Mobile
FROM
SampleRequest) AS X
ORDER BY
OrderID
Make sure that the order and data type of each column from both SELECT match.
SELECT
RXID,
DrName,
SBOID,
SBOName,
RxHonoredDate,
RxnHonoured,
CallRecievedFrom,
MobileNo
FROM
YourFirstTable AS T
UNION ALL
SELECT
RXID = NULL,
DrName = NULL,
SBOID = T.SBOID,
SBOName = NULL,
RxHonoredDate = NULL,
RxnHonoured = T.RxnHonoured,
CallRecievedFrom = T.CallRecievedFrom,
MobileNo = T.Mobile
FROM
YourSecondTable AS T

error incorporating a select within a IFNULL in MariaDB

I'm creating a view in MariaDB and i'm having trouble making it work for a couple of fields. Currently this is working:
( SELECT DISTINCT IFNULL(grades.`grade`,'No Grade')
FROM `table` grades
WHERE userinfo.`id` = grades.`id`
AND grades.`Item Name` = 'SOMEINFO'
) 'SOMENAME',
But i need to add a select where the 'No grade' is, in the following form
( SELECT DISTINCT IFNULL( grades.`grade`,
SELECT IF( EXISTS
( SELECT *
FROM `another_table`
WHERE userid = 365
AND courseid = 2
), 'Enrolled', 'Not enrolled'
)
)
FROM `table` grades
WHERE userinfo.`id` = grades.`id`
AND grades.`Item Name` = 'SOMEINFO'
) 'SOMENAME',
i know that
SELECT IF( EXISTS( SELECT *
FROM `another_table`
WHERE userid = 365
AND courseid = 2
),
'Enrolled', 'Not enrolled'
)
is working too, but now the whole thing it's giving me an error, so any suggestions would be greatly appreciated
Thanks
This looks like a subquery:
(SELECT DISTINCT IFNULL(grades.`grade`,
SELECT IF( EXISTS (SELECT *
FROM `another_table`
WHERE userid = 365 AND courseid = 2
), 'Enrolled', 'Not enrolled'
)
)
FROM `table` grades
WHERE userinfo.`id` = grades.`id` AND
grades.`Item Name` = 'SOMEINFO'
) as SOMENAME,
You are using a subquery that returns two columns in a position where a scalar subquery is expected. A scalar subquery returns one column in at most one row.
Unfortunately, there is no easy way to do what you want in MySQL, because of the restrictions on views. I would advise you to rewrite the logic so the exists is handled using a left join in the from clause.

SQL select statement in where clause

Hi there I am trying to execute a query but cannot seem to get it right.
SELECT *
FROM table
WHERE id IN (SELECT *
FROM table
WHERE description = 'A')
AND description = 'B'
Above is the query that I have got, the select * from table where description = A works as expected when ran alone I just need to make the where clause to work so I can see any id that has a description of A and B.
You will be getting multiple columns from the sub query when I assume you only want the id column:
SELECT *
FROM table
WHERE id IN (SELECT id
FROM table
WHERE description = 'A')
AND description = 'B'
No need for the select in the where clause
SELECT *
FROM table
WHERE id IN ('A', 'B')
Try this:
SELECT *
FROM table
WHERE description IN ('A', 'B')
it should be:
select * from table where id in (select id from table where description = 'A') and description = 'B'
but this query will give you zero result as you select records with description = 'A' and description = 'B', if you want to get records with either description of A or B, then you should write as
select * from table where description = 'A' or description = 'B'
or
select * from table where description in ('A','B')
SELECT distinct AnaTablo.Id , AnaTablo.FirmaAdi , AnaTablo.FirmaId , AnaTablo.KayitTarihi ,
users.Email Personel, (SELECT top 1 sabitler.Ayar from tblSabitAyarlar sabitler WHERE sabitler.Tur = 29 and sabitler.Deger in
(SELECT top 1 IslemId from tblEFaturaTakipIslem Islem WHERE AnaTablo.Id = Islem.EFaturaTakipId order by KayitTarihi desc))YapilanIslem,
AnaTablo.Eposta , AnaTablo.Aciklama
from tblEFaturaTakip AnaTablo left join AspNetUsers users on AnaTablo.PersonelId = users.Id

How to get column ordered by average of a field from some table in SQL

I think that is not easy to understand what I need reading title, so I'll explain better.
My database is like:
Table1Table2Table3 and other tables like these...
Users will insert into textfield a value like 1 and I will show them only the name that contains 1. I do this in this way:
ArrayList<String> found = new ArrayList<String>();
ArrayList<String> allTable = getAllTableInDB();
for(String table:allTable){
try {
ResultSet rs = stat.executeQuery("SELECT * FROM '"+table+"'");
while(rs.next()){
if(!found.contains(rs.getString("name")) && rs.getString("name").equals(WhatUserInserts))
found.add(rs.getString("name"));
}
} catch (SQLException ex) {
ex.printStackTrace();
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
}
}
What I want to do now is to calculate the "best" of this name found ordering by average of column v.
For one table I know that I can use something like:
SELECT name FROM table GROUP BY name ORDER BY AVG(v) DESC
How can I do the same on this limit of value of some table?
I hope I explain my question well
SOLVED in this way THANKS TO Dan P:
ArrayList<String> tables = getAllTableInDB();
String query = "SELECT * FROM (";
String union = " UNION ";
for(int i=0;i<tables.size();i++){
query+="SELECT * FROM '"+tables.get(i)+"' WHERE name LIKE '%"+find+"%'";
query = i==tables.size()-1?query:query+union;
}
query+=") GROUP BY nome ORDER BY AVG(venduti) DESC";
Assuming you want the Max or Avg of all tables this will get you the max V value for name. If you want Avgerage use AVG. I didn't exactly understand the question but I think this what you want.
SELECT Name, Max(V)
FROM
(
SELECT Name, v
FROM TABLE1
UNION
SELECT Name, v
FROM TABLE2
UNION
SELECT Name, v
FROM TABLE3
) AS AllTables
GROUP BY Name
WHERE Name = 'Jon Doe'
After commenting you asked if you could enhance performance. Yes by including the name in the where clause for each table assuming there is an index / primary key on the name. You should probably used a table valued function if you go this route.
DECLARE #Name NVARCHAR(50)
SET #Name = 'Jon Doe'
SELECT Name, Max(V)
FROM
(
SELECT Name, v
FROM TABLE1
WHERE Name = #Name
UNION
SELECT Name, v
FROM TABLE2
WHERE Name = #Name
UNION
SELECT Name, v
FROM TABLE3
WHERE Name = #Name
) AS AllTables
GROUP BY Name