I have a question on a select using join in codeigniter:
I have 2 tables.
table game
id | id_team1 | id_team2
99 | 1 | 2
table team
id | team
1 | Real
2 | Barcelona
I want to return the team to mount a showdown: Real x Barcelona
My select this as well:
$this->db->select('game.*, team.team AS team_name1, team.team AS team_name2');
$this->db->from('game');
$this->db->join('team', 'team.id = game.id_team1');
This way I can return the team first but not the second team or vice versa, changing the join to jogo.id_team2
I must return the two teams as do my join or have otherwise how can I do?
Thanks!
try this
$this->db->select('game.*, team1.team AS team_name1, team2.team AS team_name2');
$this->db->from('game');
$this->db->join('team as team1', 'team1.id = game.id_team1');
$this->db->join('team as team2', 'team2.id = game.id_team2');
Related
Scenario - I have users who are assigned different restrictions over several items. These restrictions are specified in restriction groups. Sometimes it happens that a user is a part of more than one restriction group. Sometimes, by mistake a user is assigned those restriction groups that have a conflict restriction for a common item. For example, User 123 is a part of restriction group A1 and B1 that have a common item Green Ball wherein restriction group A1 has a restriction that User 123 can access only 3 Green Balls a day while restriction group B1 says that User 123 can access only 2 Green Balls a day, thus leading to a conflict. I have to build a query that will fetch the information in such scenarios where there is a conflict. Every user belongs to a particular region, so the results will be filtered using region ID. My query should output.
UserId, Common Item, Restriction Group Name, Restriction
Tables
user - Id, userregionid
userRestriction - userId, restrictionGroup
restrictions- Item, restrictionGroup, restriction, interval // For example, Green Balls, Group A1, 3 , 1 (means 1 day)
My Effort -
select user.id,
userRestriction.restrictionGroup,
restrictions.Item,
restriction.restriction,
restriction.interval
from user left outer join userRestriction on user.Id = userRestriction.userId
left outer join restrictions on userRestriction.restrictionGroup = restriction.restrictionGroup
where user.useregionid= '12345'
group by userRestriction.userid,
user.id,
userRestriction.restrictionGroup,
restrictions.Item,
restriction.restriction,
restriction.interval,user.userregionid
having count(userRestriction.restrictiongroup)>1
I am getting nothing by running this query. This is not correct as I have data that should get resulted.
In my database, I have UserRestriction Table
UserId | RestrictionGroup
EID-999| A1
EID-888 | B1
EID-999 | C1
In the Restriction table
Item | RestrictionGroup| restriction | interval
GreenBalls| A1 | 1 | 1
Pen | B1 |1 | 7
GreenBalls|C1 |1 |30
The query should output
EID-999 | GreenBalls | A1 | 1 | 1
EID-999 | GreenBalls | C1 | 1 |30
User Table :
Id | userregionid
EID-999 | 12345
EID- 888 | 12345
D-900 | 2322
F-999 | 6767
The query should fetch only those users belonging to the specified userregionid.
I think there are some issues with your query. You can try below query -
select U.id,
UR.restrictionGroup,
R.Item,
R.restriction,
R.interval
from users U
left outer join userRestriction UR on U.Id = UR.userId
left outer join restrictions R on UR.restrictionGroup = R.restrictionGroup
where U.userregionid = 12345
group by U.id,
UR.restrictionGroup,
R.Item,
R.restriction,
R.interval
having count(UR.RestrictionGroup) >= 1
DB Fiddle
I am using laravel eloquent to get the query results. I have two tables below:
users table:
| id | department_id
| 1 | 1
| 2 | 3
| 3 | 2
department table:
| id | name
| 1 | A
| 2 | B
| 3 | C
| 4 | D
| 5 | E
How to get one unassigned ID, not existing department ID, into the users table? Example, 4 & 5 are not yet existing in users table, so how can I get 4 or 5 using an eloquent?
I am thinking of this but this is not correct.
Department::select('department.id as id')
->leftJoin('users', 'users.department_id' ,'department.id')
->pluck('id');
Does anybody know?
Try this
//here you first got all the department which is assigned to user
$assigned_dept = Users::pluck('department_id')->toArray();
$department = array_values($assigned_dept); //output:['1','3','2']
//here you can select department which is not assigned to user with limit
$user = Department::whereNotIn('id',$department)
->limit(1)->get();
hope it works for you..
You can do it like this:
Department::whereNotIn('id', User::pluck('department_id'))->get();
I believe below code will work for you :
Department::select('department.id as id')
->whereNotIn('id', User::whereNotNull('department_id')->pluck('department_id'))
->pluck('id');
From the answers others, there is a problem with the array if department_id is NULL. So, I added whereNotNull and also last() and then the problem is solved. Let me post the answer here:
Department::select('department.id as id')
->whereNotIn('id', User::whereNotNull('department_id')->pluck('department_id'))
->pluck('id')
->last(); // since I only need one row
I have a dataset looks like this:
---------------------------
cust | cost | cat | name
---------------------------
1 | 2.5 | apple | pkLady
---------------------------
1 | 3.5 | apple | greenGr
---------------------------
1 | 1.2 | pear | yelloPear
----------------------------
1 | 4.5 | pear | greenPear
-------------------------------
my hive query should now compare the cheapest price of each item the customer bought. So I want now to get the 2.5 and 1.2 into one row to get its difference. Since I am new to Hive I don't now how to ignore everything else until I reach next category of item while I still kept the cheapest price in the previous category.
you can use like below:
select cat,min(cost) from table group by cost;
Given your options (brickhouse UDFs, hive windowing functions or a self-join) in Hive, a self-join is the worst way to do this.
select *
, (cost - min(cost) over (partition by cust)) cost_diff
from table
You could create a subquery containing the minimum cost for each customer, and then join it to the original table:
select
mytable.*,
minCost.minCost,
cost - minCost as costDifference
from mytable
inner join
(select
cust,
min(cost) as minCost
from mytable
group by cust) minCost
on mytable.cust = minCost.cust
I created an interactive SQLFiddle example using MySQL, but it should work just fine in Hive.
I think this is really a SQL question rather than a Hive question: If you just want the cheapest cost per customer you can do
select cust, min(cost)
group by cust
Otherwise if you want the cheapest cost per customer per category you can do:
select cust, cat, min(cost)
from yourtable
groupby cust, cat
I am trying to achieve the following result (the first line is header)
Level 1 | Level 2 | Level 3 | Level 4 | Person
Technicals | Development | Software | Team leader | Eric
Technicals | Development | Software | Team leader | Steven
Technicals | Development | Software | Team leader | Jana
How can I do so? I tried to use the following code. The first part is to create the hierarchy which works fine. The second part is to have the date in the above mentioned table is a pretty painful.
SELECT * FROM ( /* level2 */
SELECT * FROM ( /* level1 */
SELECT * FROM arc.localnode /*create hierarchy */
WHERE tree_id = 2408362
CONNECT BY PRIOR node_id = parent_id
START WITH parent_id IS NULL ) l1node
LEFT JOIN names on l1node.prent_id = names.name_id ) l2node
At this point, I am quite lost. A bit of guidance and suggestion would be a lot of help :-)
There are two tables. The first table has data like this:
NODE_ID | PREV_ID | NEXT_ID | PARENT_ID
1421864 3482917 1421768
3482981 3482917 1421866 1421768
3482911 3060402 3482913 1421768
3482917 1421864 3482981 1421768
This is a complicated because it is in hieraracy. So obviously a PARENT_ID can be the NODE_ID of some other PARENT_ID. Similarly the parent_ID can be the PREV_ID and NEXT_ID.
The names are in seperate table with name_id. The name ID in this table is similar to NODE_ID of the main table in hieraracy.
You can use the Stragg Package mentioned in AskTom in the below link
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2196162600402
Your can also refer the below link in oracle forum
https://forums.oracle.com/forums/thread.jspa?threadID=2258996
Kindly post create and insert statements for your requirement so that we can test it and confirm
I am using the following LINQ query for my profile page:
var userData = from u in db.Users
.Include("UserSkills.Skill")
.Include("UserIdeas.IdeaThings")
.Include("UserInterests.Interest")
.Include("UserMessengers.Messenger")
.Include("UserFriends.User.UserSkills.Skill")
.Include("UserFriends1.User1.UserSkills.Skill")
.Include("UserFriends.User.UserIdeas")
.Include("UserFriends1.User1.UserIdeas")
where u.UserId == userId
select u;
It has a long object graph and uses many Includes. It is running perfect right now, but when the site has many users, will it impact performance much?
Should I do it in some other way?
A query with includes returns a single result set and the number of includes affect how big data set is transfered from the database server to the web server. Example:
Suppose we have an entity Customer (Id, Name, Address) and an entity Order (Id, CustomerId, Date). Now we want to query a customer with her orders:
var customer = context.Customers
.Include("Orders")
.SingleOrDefault(c => c.Id == 1);
The resulting data set will have the following structure:
Id | Name | Address | OrderId | CustomerId | Date
---------------------------------------------------
1 | A | XYZ | 1 | 1 | 1.1.
1 | A | XYZ | 2 | 1 | 2.1.
It means that Cutomers data are repeated for each Order. Now lets extend the example with another entities - 'OrderLine (Id, OrderId, ProductId, Quantity)andProduct (Id, Name)`. Now we want to query a customer with her orders, order lines and products:
var customer = context.Customers
.Include("Orders.OrderLines.Product")
.SingleOrDefault(c => c.Id == 1);
The resulting data set will have the following structure:
Id | Name | Address | OrderId | CustomerId | Date | OrderLineId | LOrderId | LProductId | Quantity | ProductId | ProductName
------------------------------------------------------------------------------------------------------------------------------
1 | A | XYZ | 1 | 1 | 1.1. | 1 | 1 | 1 | 5 | 1 | AA
1 | A | XYZ | 1 | 1 | 1.1. | 2 | 1 | 2 | 2 | 2 | BB
1 | A | XYZ | 2 | 1 | 2.1. | 3 | 2 | 1 | 4 | 1 | AA
1 | A | XYZ | 2 | 1 | 2.1. | 4 | 2 | 3 | 6 | 3 | CC
As you can see data become quite a lot duplicated. Generaly each include to a reference navigation propery (Product in the example) will add new columns and each include to a collection navigation property (Orders and OrderLines in the example) will add new columns and duplicate already created rows for each row in the included collection.
It means that your example can easily have hundreds of columns and thousands of rows which is a lot of data to transfer. The correct approach is creating performance tests and if the result will not satisfy your expectations, you can modify your query and load navigation properties separately by their own queries or by LoadProperty method.
Example of separate queries:
var customer = context.Customers
.Include("Orders")
.SingleOrDefault(c => c.Id == 1);
var orderLines = context.OrderLines
.Include("Product")
.Where(l => l.Order.Customer.Id == 1)
.ToList();
Example of LoadProperty:
var customer = context.Customers
.SingleOrDefault(c => c.Id == 1);
context.LoadProperty(customer, c => c.Orders);
Also you should always load only data you really need.
Edit: I just created proposal on Data UserVoice to support additional eager loading strategy where eager loaded data would be passed in additional result set (created by separate query within the same database roundtrip). If you find this improvement interesting don't forget to vote for the proposal.
(You can improve performance of many includes by creating 2 or more small data request from data base like below.
According to my experience,Only can give maximum 2 includes per query like below.More than that will give really bad performance.
var userData = from u in db.Users
.Include("UserSkills.Skill")
.Include("UserIdeas.IdeaThings")
.FirstOrDefault();
userData = from u in db.Users
.Include("UserFriends.User.UserSkills.Skill")
.Include("UserFriends1.User1.UserSkills.Skill")
.FirstOrDefault();
Above will bring small data set from database by using more travels to the database.
Yes it will. Avoid using Include if it expands multiple detail rows on a master table row.
I believe EF converts the query into one large join instead of several queries. Therefore, you'll end up duplicating your master table data over every row of the details table.
For example: Master -> Details. Say, master has 100 rows, Details has 5000 rows (50 for each master).
If you lazy-load the details, you return 100 rows (size: master) + 5000 rows (size: details).
If you use .Include("Details"), you return 5000 rows (size: master + details). Essentially, the master portion is duplicated over 50 times.
It multiplies upwards if you include multiple tables.
Check the SQL generated by EF.
I would recommend you to perform load tests and measure the performance of the site under stress. If you are performing complex queries on each request you may consider caching some results.
The result of include may change: it depend by the entity that call the include method.
Like the example proposed from Ladislav Mrnka, suppose that we have an entity
Customer (Id, Name, Address)
that map to this table:
Id | Name | Address
-----------------------
C1 | Paul | XYZ
and an entity Order (Id, CustomerId, Total)
that map to this table:
Id | CustomerId | Total
-----------------------
O1 | C1 | 10.00
O2 | C1 | 13.00
The relation is one Customer to many Orders
Esample 1: Customer => Orders
var customer = context.Customers
.Include("Orders")
.SingleOrDefault(c => c.Id == "C1");
Linq will be translated in a very complex sql query.
In this case the query will produce two record and the informations about the customer will be replicated.
Customer.Id | Customer.Name | Order.Id | Order.Total
-----------------------------------------------------------
C1 | Paul | O1 | 10.00
C1 | Paul | O2 | 13.00
Esample 2: Order => Customer
var order = context.Orders
.Include("Customers")
.SingleOrDefault(c => c.Id == "O1");
Linq will be translated in a simple sql Join.
In this case the query will produce only one record with no duplication of informations:
Order.Id | Order.Total | Customer.Id | Customer.Name
-----------------------------------------------------------
O1 | 10.00 | C1 | Paul