I have this query made in codeigniter using active record
$this->db->select('products_main.*, images_main.*, items_main.*, product_tags.*');
$this->db->from('products_main');
$this->db->join('images_main','products_main.product_tag = images_main.img_tag AND products_main.product_id = images_main.pro_img_id');
$this->db->join('items_main','products_main.product_id = items_main.pro_items_id');
$this->db->join('product_tags','products_main.product_id = product_tags.pro_tag_id');
$this->db->where('products_main.product_id',$p_id);
$this->db->where('products_main.status','active');
$this->db->group_by('products_main.product_id');
$query = $this->db->get();
My goal is to:
Grab one product from products_main that matches the input from $p_id
Grab all the photos for that one product from the images_main table
Grab all the items that have the product_id of the product I have found
Grab the row in the product_tags table that match the product_id of the product i have found.
I started a test fiddle here but have not filled out the query part yet as I do not know what to put. fiddle
You don't have any problem within your query, but as you group by product id, you may only get one result, but you can group by image_id instead, i've created the same in my localhost with the database you've created a fiddle and tried your solution, your only problem i see was as you don't join on left, the query can't find any exact matches, so try to join on left, also i've changed your query a little bit to prevent the database error with the given structure in your fiddle, so change it if you have them like that in your database ( commented them ) :
$this->db->select('p.*, im.*, i.*, pt.*');
$this->db->from('products_main as p');
// img_tag -> image_tag
$this->db->join('images_main as im',
'p.product_tag = im.image_tag
AND p.product_id = im.product_id','left'); // pro_img_id -> product_id
$this->db->join('items_main as i',
'p.product_id = i.product_id','left'); // pro_items_id -> product_id
$this->db->join('product_tags as pt',
'p.product_id = pt.product_id','left'); // pro_tag_id -> product_id
$this->db->where('p.product_id',"23"); // i have given example id as 23
$this->db->where('p.status','active');
$query = $this->db->get();
return $query->result_array();
Related
! have three table
inventories
enter image description here
warehouses
enter image description here
inventory_has_warehouses
enter image description here
I have use laravel yajra datatable. i need sum and search of starting_balance this field in inventory_has_warehouses pivot table
my code:
$id = Auth::user()->id;
$row = Inventory::with('contact')->with('warehouse')
->select(
'inventories.*',
DB::raw('SUM(inventory_has_warehouses.starting_balance) as total')
)
->leftJoin('inventory_has_warehouses', 'inventory_has_warehouses.inventory_id', '=', 'inventories.id')
->leftJoin('warehouses', 'warehouses.id', '=', 'inventory_has_warehouses.warehouse_id')
->where('inventories.subscriber_id',$id)
->groupBy('inventories.id');
$datatable = DataTables::of($row)
->filterColumn('total', function($query, $keyword) {
$query->whereRaw('sum(inventory_has_warehouses.starting_balance) like ?', ['%'.$keyword.'%']);
})
return $datatable->make(true);
but i fount this type of error
Exception Message:↵↵SQLSTATE[HY000]: General error: 1111 Invalid use
of group function (SQL: select count() as aggregate from (select
inventories., SUM(inventory_has_warehouses.starting_balance) as
total from inventories left join inventory_has_warehouses on
inventory_has_warehouses.inventory_id = inventories.id left
join warehouses on warehouses.id =
inventory_has_warehouses.warehouse_id where
inventories.subscriber_id = 2 and inventories.status = 1 and
(LOWER(inventories.itemcode) LIKE %1% or
LOWER(inventories.purchasedescription) LIKE %1% or exists (select
* from contacts where inventories.supplier = contacts.id and LOWER(contacts.name) LIKE %1%) or
(sum(inventory_has_warehouses.starting_balance) like %1%)) group by
inventories.id) count_row_table)
mysql query
select inventories., SUM(inventory_has_warehouses.starting_balance)
as total from inventories left join inventory_has_warehouses on
inventory_has_warehouses.inventory_id = inventories.id left join
warehouses on warehouses.id = inventory_has_warehouses.warehouse_id
where inventories.subscriber_id = 2 and inventories.status = 1 and
(LOWER(inventories.itemcode) LIKE %1% or
LOWER(inventories.purchasedescription) LIKE %1% or exists (select *
from contacts where inventories.supplier = contacts.id and
LOWER(contacts.name) LIKE %1%) or
(sum(inventory_has_warehouses.starting_balance) like %1%)) group by
inventories.id
$id = Auth::user()->id;
$row = DB::table('inventories')->select('inventories.*','contacts.name',DB::raw('SUM(inventory_has_warehouses.starting_balance) as total'))
->leftJoin('contacts', 'inventories.supplier', '=', 'contacts.id')
->leftJoin('inventory_has_warehouses', 'inventories.id', '=', 'inventory_has_warehouses.inventory_id')
->where('inventories.subscriber_id',$id)
->groupBy('inventory_has_warehouses.inventory_id');
if ($keyword = $request->get('search')['value']) {
$row->having(DB::raw('SUM(inventory_has_warehouses.starting_balance)'), 'like', '%'.$keyword.'%');
$row->orHaving('inventories.itemcode', 'like', '%'.$keyword.'%');
$row->orHaving('inventories.purchasedescription', 'like', '%'.$keyword.'%');
$row->orHaving('contacts.name', 'like', '%'.$keyword.'%');
}
$datatable = DataTables::of($row)
->filterColumn('total', function($query, $keyword) {
})
return $datatable->make(true);
try to group by inventory_has_warehouses.inventory_id
Edited answer:
Your really giving hardtime for someone to read your query and give you help but to correct your query here is a reformatted query with corrections:
SELECT
inventories.*,
SUM(inventory_has_warehouses.starting_balance) as total
FROM
inventories LEFT JOIN inventory_has_warehouses
ON
inventory_has_warehouses.inventory_id = inventories.id LEFT JOIN warehouses
ON
warehouses.id = inventory_has_warehouses.warehouse_id
WHERE
inventories.subscriber_id = 2
AND
inventories.status = 1
AND
(LOWER(inventories.itemcode) LIKE '%1%' or LOWER(inventories.purchasedescription)
LIKE '%1%' OR EXISTS
(SELECT
*
FROM
contacts
WHERE
inventories.supplier = contacts.id
AND
LOWER(contacts.name) LIKE '%1%')
OR
(SUM(inventory_has_warehouses.starting_balance) LIKE '%1%')) GROUP BY inventories.id
the problem with query you sent is your like statement only have this:
LIKE %1%
this statement expects strings and it only says:
inventories.
this should be specific to a column you need or just use inventories.* to display all columns of that table but the error still doesn't make sense because it says and:
select count() as aggregate
maybe one of those would solve but upon reformatting your code I notice firstly the syntax error but this is very basic maybe you can start on just running a very simple query for the moment this might be the query that would work for you:
SELECT
inventories.id AS inventory_id,
warehouses.id,
SUM(inventory_has_warehouses.starting_balance) AS total
FROM
inventories LEFT JOIN inventory_has_warehouses
ON inventories.id = inventory_has_warehouses.inventory_id
LEFT JOIN
warehouses
ON warehouses.id = inventory_has_warehouses.warehouse_id
GROUP BY
inventory_has_warehouses.inventory_id
from this start adding the conditions one by one until the error appears again (do this on mysql query window not through laravel code) not yet sure how laravel handles sql queries but the format you sent will really cause an error and also if your going to post a question here make sure to make it reader friendly or someone might slam you cause its hard to read a code that is not properly formatted. ;)
also one thing I forgot make sure that the inventories.id is the primary key of that table or this will still cause you an error refer to this link for more details https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html
Hey I tried this thread but it doesn't work and i can't figure out why...
here's my SQL:
SELECT * FROM gone_items
LEFT JOIN items
ON gone_items.item_ID=items.ID
WHERE
gone_items.aus_ID='$ID'
ORDER BY items.name ASC
Now, I fetch that via PHP and have a $row and try another mysql to get the individual ID's of the gone_items table. But if i use $row['ID'] I get the ID of the items.ID not the one from gone_items.ID.
I tried setting the variable manually in the first query but it doesn't work.
I also tried this: MYSQL Left join A.table and b.table while retaining a.table id
Also didn't help me...
All I want is to retain the ID (Primary key) from the gone_items table..
Can anyone please tell me what I'm doing wrong ?
Love
Gram
EDIT
//Query for Joined infos
$sqlx="SELECT foto_res_ausgeliehene_geg.ID, foto_res_ausgeliehene_geg.aus_ID, foto_res_ausgeliehene_geg.geg_ID, foto_res_ausgeliehene_geg.zusaetzliches, foto_res_gegenstaende.ID, foto_res_gegenstaende.bezeichnung, foto_res_gegenstaende.seriennummer, foto_res_gegenstaende.interne_seriennummer, foto_res_gegenstaende.zusaetzliches FROM foto_res_ausgeliehene_geg
LEFT JOIN foto_res_gegenstaende
ON foto_res_ausgeliehene_geg.geg_ID=foto_res_gegenstaende.ID
WHERE
foto_res_ausgeliehene_geg.aus_ID='$ID'
ORDER BY foto_res_gegenstaende.bezeichnung ASC
";
$ergebnisx = mysqli_query($db,$sqlx);
while ($zeilex = mysqli_fetch_assoc($ergebnisx))
{
//Query for individual infos
$sqly="SELECT * FROM foto_res_ausgeliehene_geg
WHERE `geg_ID`='".$zeilex['ID']."'
AND `aus_ID`='$ID'
GROUP BY `geg_ID`
";
$ergebnisy = mysqli_query($db,$sqly);
while ($zeiley = mysqli_fetch_assoc($ergebnisy))
{};
Now I did select all items individually. The foto_res_ausgeliehene_geg.ID still merges with the foto_res_gegenstanede.ID due to the LEFT JOIN.
So if i access $zeilex['ID'] im getting the ID of foto_res_gegenstaende.ID.
Would it help if I rename the ID field in one of the tables into lets say item_ID ?
Thanks alot.
Love
Gram.
Instead of using select *, you should explicitly state what items you want to select. Else you can get conflicts with multiple id fields. In your case something like:
select gone_items.id, gone_items.column1, gone_items.column2, items.column1, items.column2
It is also considered good practice, to limit the amount of data there is being selected. But is meanwhile also a highly debateable what is the right way. Performance issue in using SELECT *?
WORKS!
I simply renamed one of the Primary ID keys to something else, in this case, one of them got ID -> item_ID. The other one still is ID that way the left join won't merge them.
yolo
EDIT
WORKING CODE
$sqlx="SELECT foto_res_ausgeliehene_geg.item_ID, foto_res_ausgeliehene_geg.aus_ID, foto_res_ausgeliehene_geg.geg_ID, foto_res_ausgeliehene_geg.zusaetzliches, foto_res_gegenstaende.ID, foto_res_gegenstaende.bezeichnung, foto_res_gegenstaende.seriennummer, foto_res_gegenstaende.interne_seriennummer, foto_res_gegenstaende.zusaetzliches FROM foto_res_ausgeliehene_geg
LEFT JOIN foto_res_gegenstaende
ON foto_res_ausgeliehene_geg.geg_ID=foto_res_gegenstaende.ID
WHERE
foto_res_ausgeliehene_geg.aus_ID='$ID'
ORDER BY foto_res_gegenstaende.bezeichnung ASC
";
$ergebnisx = mysqli_query($db,$sqlx);
while ($zeilex = mysqli_fetch_assoc($ergebnisx))
{
//Query for individual infos
$sqly="SELECT * FROM foto_res_ausgeliehene_geg
WHERE `item_ID`='".$zeilex['item_ID']."'
";
$ergebnisy = mysqli_query($db,$sqly);
while ($zeiley = mysqli_fetch_assoc($ergebnisy))
{
I am trying to only show results from table inventoryfolders if the id does not exist in table newlisting.
Here is my query:
$sql = "SELECT *
FROM avirobust.inventoryfolders
WHERE parentFolderID = '".$foname."'
AND agentID = '".$mne."'
AND parentFolderID NOT IN (SELECT folderID FROM marketplace.newlisting)";
However it never returns a result even if newlisting has no data in it.
I know that join can work but can I use something like in my query above? If so what did I do wrong in my query?
You can try use this code
SELECT inventoryfolders.*
FROM avirobust.inventoryfolders LEFT JOIN marketplace.newlisting on (inventoryfolders.parentFolderID = newlisting.folderID)
WHERE parentFolderID = '".$foname."'
AND agentID = '".$mne."'
AND newlisting.folderID is NULL
It will return all records from inventoryfolders where no corresponding rows in newlisting
I have tow tables, the first is mda_alert_info and the second is key_contacts_info. For each alert set up there may be multiple corresponding contacts. Both tables are linked by 3 columns mda_id, stage_id and ref_number and during the query I will have to pass figures values for them
How do I get all what I want from both tables in one statement. Below are the individual SELECT statements.
$result = mysql_query("SELECT `mda_name`, `project_name`, `ipc_id` FROM `mda_alert_info` WHERE `stage_id`=1 AND `mda_id`=2 AND `ref_number`= '444'");
This will always return one record
$result = mysql_query("SELECT `contact_role`, `contact_email`, `contact_ph_number` FROM `key_contacts_info` WHERE `stage_id`=1 AND `mda_id`=2 AND `role`=0 AND `ref_number`='444'");
This may return multiple records
I tried for a while and couldn't get it to work so I tried adding another field called 'me' to both tables which is basically concatting mda_id and stage_id strings then I tried the query below.
$result = mysql_query("SELECT key_contacts_info.contact_role, key_contacts_info.contact_email, key_contacts_info.contact_ph_number, mda_alert_info.mda_name, mda_alert_info.project_name, mda_alert_info.ipc_id FROM key_contacts_info LEFT JOIN mda_alert_info ON key_contacts_info.me = mda_alert_info.me WHERE stage_id=1 AND mda_id=2 AND role=0 AND ref_number='444'");
But it's still not working. What am I doing wrong and how do I get it to work.
UPDATE:
Sorry but I should clarify something on the relationship between the tables the three columns exist on each table but are not primary keys on either of the tables
SELECT a.*, b.*
FROM mda_alert_info a
INNER JOIN key_contacts_info b
ON a.mda_id = b.mda_id AND
a.stage_id = b.stage_id AND
a.ref_number = b.ref_number
WHERE b.role = 0 AND
a.stage_id = 1 AND
a.mda_id = 2 AND
a.ref_number = '444'
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins
select
a.mda_name,
a.project_name,
a.lpc_id,
k.contact_role,
k.contact_email,
k.contact_ph_number
from mda_alert_info a
join key_contacts_info k
on a.state_id = k.state_id
and a.mda_id = k.mda_id
and a.ref_number = k.ref_number
where a.state_id = 1
and a.mda_id = 2
and a.ref_number = '444'
and k.role = 0
;
I have two tables: Users and Groups
In my table "Users", there is a column called "ID" for all the user ids.
In my table "Groups" there is a column called "Participants", fields in this column are filled with all the user ids like this "PID_134,PID_489,PID_4784," - And there is a column "ID" that identifies a specific group.
Now what i want to do, i want to create a menu that shows all the users that are not yet in this particular group.
So i need to get all the user ids, that are not yet in the Participants column of a group with a particular ID.
It would be cool if there was a single mysql query for that - But any PHP + MySQL solutions are okay, too.
How does that work? Any guesses?
UPDATE:
i know, that's not code, but is there a way I could do something like this that would return me a list of all the users?
SELECT *
FROM users, groups
WHERE groups.participants NOT LIKE '%PID_'users.id'%' AND groups.id = 1;
Something like this. You just get rid of "PID_" part of ID.
SELECT * FROM [users] WHERE [id] NOT IN
(SELECT replace(id,'PID_','') FROM groups WHERE group_name='group1')
Group1 would be your variable - group id/name of menu that you've opened.
You can select from multiple tables as shown below:
SELECT * from users, groups WHERE users.id != groups.participants AND groups.id = 1;
This will list all users who are not in group id 1; A more elegant solution can be found by using joins, but this is simple and will do the trick.
I believe something like that should help:
SELECT * FROM users WHERE users.id NOT IN (SELECT groups.participants FROM groups)
But this works only if your DB is normalized. So for your case I see only PHP + MySQL solution. Not very elegant, but it does the job.
<?php
$participants_array = mysql_query("SELECT participants FROM groups");
$ids = array();
while ($participant = mysql_fetch_assoc($participants_array))
{
$id = explode(',', $participant['participant']);
foreach ($id as $instance)
{
if (!in_array($instance, $ids)) $ids[] = $instance;
}
}
$participants = implode(',', $ids);
$result = mysql_query("SELECT * FROM users WHERE id NOT IN ( $participants )");
But I highly recommend normalizing the database.