Select multiple columns prioritized into one - php

Database schema
I have these three main tables:
products
groups
users
And these two pivot table:
product_user
group_user
Each user has a group.
Each product has a price which may be overriden by a price in the product_user pivot table or by a price in the group_user table.
Problem
Now I know how to join these tables and everything but with my current solution I am only able to select each of these prices to a separate column like price, user_price and group_price and prioritize them using PHP.
Question
Is it possible to select these 3 columns from these different tables and prioritize them into one column using only Sql?
So if there is a user-specific price selected this price into price, if not and there is a group-specific price selected this one and if there is no special price select the products default price.
Laravel specific solution
As #Shadow pointed out below, the solution is the MySQL coalesce function.
Using Laravel's query builder I was now able to achieve what I want using this statement:
$query->addSelect(
DB::raw('coalesce(product_user.price, group_product.price, products.price) as price')
);

Use the coalesce() function to return the 1st non-null value from its parameters.
select coalesce(product_user.price, group_user.price, product.price) as price
from ...
Since you have not shared the exact schema with me, I cannot provide mpre specific help. I assume that there are price columns in the tables.

Related

Copy rows in MySQL table multiple times and adding additional column

I have created MySQL table in database. Table name is products and the columns are( prodict_id(pk) product_name and pack_size) as shown in the figure below.
What I want to do is , copy all the rows in the table and add additional information in additional column called (buyer_name) so each product is associated with a specific buyer which makes it unique
Is there a way I can achieve this using query? Where I can give a list of buyers and it attaches it to all rows in table?
p.s I have almost 700 rows in my table and I have 12 buyers, so if I do it manually, it will consume too much time
As per your comment your buyer details are in a table and you want to map each product with each of the buyer then you can write your insert query like below:
insert into newtable
select t1.*, t2.buyername from products t1 join buyers t2
DEMO
You can use where clause also to filter some results from either of the table.
It seems you want to automate the data insertion from product table to buyer table. How about, if you select that fetches all the buyers first and then you insert into buyer table.
It can be based on subquery where insert is the outer one and select is the nested one.
Good luck !

SELECT FROM 100 tables in 1 database

I am trying to SELECT id, description, title FROM table1, table2, table100
Say I get this working, is it better for me to just combine all my tables in phpmyadmin?
The problem is I have around 100 tables all of different categories of books so I want to keep them seperated in their individual tables.
I am trying to make a search engine that searches all the books in the entire database. All tables have the same column names.
So really all I really am trying to do is search the entire database's tables for an id, description, title. My search works, just I can only search 1 table and every solution online I have found only really works efficiantly with 2 or 3 tables.
Thanks in advance.
The best is to redesign your database, everything into a single table with an additional "category" column.
in the meantime, you can create a view which union the tables with an additional column for the category.
I recommend redesign the model and unifique this 100 tables to 1, and add a new column with category but integer value, not string value. In this way, you can index the category column with the other fields (id, description, title) for speed up the query.
This resolution is more easy for avoid pain later.
I recommend keeping one table A with id, description, title, category and create another table B with categories. Table A has to have a foreign key with table categories. Then create a query to retrieve the books with a specific category.
Example:
SELECT id, description, title, category FROM books WHERE category = "drama"
I think it speaks to the database design itself as mentioned by most here. You've a few options depending on how much time you have on your hands:
(Short Term / Quick Fix) Central table with all your current fields plus category as a flag to differentiate between the current tables you have. So your insert will be something like "INSERT INTO newtable (ID,AssetID,ServiceID,Category) SELECT id, description, title, 'Fiction' FROM table1 ;"
If you tables are incrementally named like table1, table2 upto table100, you could then maybe write a quick php script that will iterate through the insert loop while incrementing on table on each iteration until the last table.
In the long run, you could invest in a json field that will house all your other data excluding keys that pertaining to a single entry

Unique Columns in SQL Views

In my database I have one table that contains a complete list of products, and another table that contains the same list of products on the x-axis, with a list of customers on the y-axis, where the value for each product can be 1 or 0 depending on whether that customer can view that product. My SQL looks like this:
SELECT products.product_code, products.product_type, products.product_category, products.product_title, products.product_description
FROM product_lists
INNER JOIN products
ON product_lists.product_code=products.product_code
WHERE product_lists.customer="1"
ORDER BY products.product_code
My problem is that I would like to create a view of this result for each customer to use as that customers product table, however when I create it I get the message "This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available." even though the product_code field is set as a primary key in both the products table and the product_lists table.
How can I create a join/view that uses the primary key from the table(s) it was created from? In short I would like the product_code field to become the primary key of my view.
Thanks!
I think the problem is the join. You can fix this by moving the condition to the where clause. MySQL doesn't allow subqueries in the from, but it does in the where:
SELECT p.product_code, p.product_type, p.product_category, p.product_title, p.product_description
FROM products p
WHERE EXISTS (SELECT 1
FROM product_lists pl
WHERE pl.product_code = p.product_code AND
pl.customer = 1
)
ORDER BY p.product_code;

How to join multiple fields data from two different tables in SQL?

I'm using this query to join data from two different tables. Invoice table holding data, with stock code and supplier code. Please check my query point out my error in query.
inv_code field holding stock code and supplier code. My second table is
cb_chart_temp having acc_code, and acc_name;
SELECT
`invoice`.`inv_code`,
`cb_chart_temp.acc_name`,
`invoice.sup_id`,
`cb_chart_temp`.`acc_name`
FROM
`invoice`,
`cb_chart_temp`
WHERE
inv_no LIKE 'PI%'
invoice.inv_code=cb_chart_temp.acc_code
AND invoice.sup_id=cb_chart_temp.acc_code
My result should look like this!
inv_code acc_name sup_id sup_name
ST-00001 Stock Name SUP-00001 Supplier Name
It misses an AND, as already pointed out by #Lion, plus it is doubtful that the join of keys is correct. As you have it, inv_code, acc_code, and sup_id all belong to the same domain, i.e., all of them are, e.g., invoice codes.

Querying multiple tables in MySQL

I am trying to fetch data from multiple tables depending on what is selected in a dropdown menu. My dropdown menu consists of a list of ID's (001, 002, etc).
Once a user selects one of them, I am using AJAX to dynamically fetch data depending on what was selected. I was able to fetch a single value depending on what was selected but having problems when multiple tables are involved.
My tables are set up like this:
Inventory table:
inven_ID (primary)
cost
description
Order table:
order_ID(primary)
orderdesc
Sale table:
inven_ID
order_ID
quantity
primary(inven_ID,order_ID)
My query is as follows:
$QRY = "SELECT
inven_ID,
order_ID,
cost,
description
FROM
Inventory,
Order,
Sale
WHERE Inventory.inven_ID = Sale.inven_id
AND Sale.order_ID = Order.order_ID
AND Order.order_ID ='".$q."'";
The $q represents the value from the dropdown menu (which I checked is valid). I am getting the error Column 'inven_ID' in field list is ambiguous. Basically, when they select some order id from the drop down (say 001), it looks for order_ID in my Order table, and fetches the inven_ID/cost/description of that particular order ID.
Eg. if someone ordered parts xy, yz, xyz for cost 10,20,30.
Selecting 001 would bring up:
001 xy 10
001 yz 20
001 xyz 30
I think I am not joining tables properly since the error says its ambiguous.
Any help on this?
edit: yes that fixed the problem, quite obvious that I did not catch it.
In the column list of your select, you just need to specify which inven_ID you want to retrieve. For instance:
SELECT Inventory.inven_ID, ...
The error is pretty obvious. inven_ID is ambiguous because you have it in Sale and in Inventory. Use a specifier like Sale.inven_ID or Inventory.inven_ID.

Categories